package MyTest;

import java.util.Stack;

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if(ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            }else {
                if(stack.isEmpty()) {
                    return false;
                }
                char top = stack.peek();//栈里面没元素会抛异常
                if(ch == ')' && top == '(' || ch == '}' && top == '{' || ch == ']' && top == '[') {
                    stack.pop();
                }else {
                    return false;
                }
            }
        }
        if(!stack.isEmpty()) {
            return false;
        }
        return true;
    }
}
